import { login, logout, getUserInfo } from '@/api/user'
import router, { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { MD5Encrypt } from '@/utils'

const state = {
  /**
   * 用户Token
   */
  token: getToken(),
  /**
   * 用户名
   */
  userName: "",
  /**
   * 头像路径
   */
  avatarPath: "",
  /**
   * 个人说明
   */
  statement: "",
  /**
   * 用户类型代码列表
   */
  userTypeCodes: []
}

const mutations = {
  /**
   * 设置Token
   * @param {*} state 
   * @param {String} token 
   */
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  /**
   * 设置用户名
   * @param {*} state 
   * @param {String} username 
   */
  SET_USERNAME: (state, userName) => {
    state.userName = userName
  },
  /**
   * 设置头像路径
   * @param {*} state 
   * @param {String} avatarPath 
   */
  SET_AVATARPATH: (state, avatarPath) => {
    state.avatarPath = avatarPath
  },
  /**
   * 设置(用户)描述
   * @param {*} state 
   * @param {String} statement 
   */
  SET_STATEMENT: (state, statement) => {
    state.statement = statement
  },
  /**
   * 设置用户类型列表
   * @param {*} state 
   * @param {Array} userTypeCodes 
   */
  SET_USERTYPECODES: (state, userTypeCodes) => {
    state.userTypeCodes = userTypeCodes
  }
}

const actions = {
  /**
   * 登录
   * @param {*} param0 
   * @param {*} userInfo 
   * @returns 
   */
  login({ commit }, userInfo) {
    const param = Object.assign({}, userInfo)
    param.password = MD5Encrypt(param.password)
    return new Promise((resolve, reject) => {
      login(param)
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
    })
  },
  /**
   * 获取用户信息
   * @param {*} param0 
   * @returns 
   */
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('验证失败，请重新登录')
        }
        const { userName,avatarPath,statement,userTypeCodes} = data
        if (!userTypeCodes || userTypeCodes.length <= 0) {
          reject('用户类型代码不能为空或空数组')
        }
        commit('SET_USERNAME', userName)
        commit('SET_AVATARPATH', process.env.VUE_APP_BASE_DOWNLOAD_API + avatarPath)
        commit('SET_STATEMENT', statement)
        commit('SET_USERTYPECODES', userTypeCodes)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 登出
   * @param {*} param0 
   * @returns 
   */
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USERTYPES', [])
        removeToken()
        resetRouter()
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  /**
   * 重置Token
   * @param {*} param0 
   * @returns 
   */
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USERTYPES', [])
      removeToken()
      resolve()
    })
  },
  /**
   * 改变用户类型
   * @param {*} param0 
   * @param {Array} userTypeCode
   */
  async changeUserTypes({ commit, dispatch }, userTypeCode) {
    const token = userTypeCode + '-token'
    commit('SET_TOKEN', token)
    setToken(token)
    const { userTypeCodes } = await dispatch('getUserInfo')
    resetRouter()
    const accessRoutes = await dispatch('permission/generateRoutes', userTypeCodes, { root: true })
    router.addRoutes(accessRoutes)
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
